package com.shop.vo;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

public class OssUtil {

    private static String ENDPOINT = "oss-cn-beijing.aliyuncs.com";
    private static String ACCESSKEYID = "LTAI4GKFAYpfwW3is2KsrKxm" ;
    private static String ACCESSKEYSECRET = "c4IxijRBb5sIETK9fAkzHiSK3F2CTo" ;
    private static String BUCKET = "websites-images"; //存儲到OSS哪那個文件裏




    public static String uploadImg(MultipartFile file) throws IOException {
        String imgFileName = "web-images/";//保存到阿里云websites-images里的web-images文件夹名
        String endpoint = OssUtil.ENDPOINT; //上面的值
        String accessKeyId = OssUtil.ACCESSKEYID;
        String accessKeySecret = OssUtil.ACCESSKEYSECRET;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        InputStream inputStream = file.getInputStream();
        String originName = file.getOriginalFilename();//獲取上传的文件名
        String fileName =  imgFileName+UUID.randomUUID().toString()+'-'+originName;//保存路径为文件夹+UUID+文件名
        ossClient.putObject(OssUtil.BUCKET,fileName, inputStream);
        ossClient.shutdown();
        //前面的内容，阿里云文档上都有
        //上传成功后，获取文件路径+文件名；
        String urlName = URLEncoder.encode(fileName, "UTF-8");//防止中文和特殊字符乱码
        String imgUrl =  "https://" + BUCKET+"."+ENDPOINT+ File.separator  +urlName;//返回的图片路径，oss根目录加上阿里云的ENDPOINT地址，File.separator =\
        return imgUrl;//将图片路径返回
    }


    /**
     * 删除图片的方法 未调用是否成功
     * @param objectName
     */
    public static void deleteImg(String objectName) {
    //  objectName = "https://websites-images.oss-cn-beijing.aliyuncs.com/web-images/16414b6f-4fdc-4454-b36a-94408e7a6a31-3.jpg";
        objectName=objectName.substring(52);
        System.out.println(objectName);
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESSKEYID, ACCESSKEYSECRET);
        //BUCKET所在的存储
        // 删除文件。如需删除文件夹，请将ObjectName设置为对应的文件夹名称。如果文件夹非空，则需要将文件夹下的所有object删除后才能删除该文件夹。
        ossClient.deleteObject(BUCKET, objectName);

        ossClient.shutdown();


    }
}

